package com.hundsun.cprs.yyt.service.account.service.impl;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.common.redis.RedisDistributedLock;
import com.hundsun.cprs.yyt.service.account.dao.AccountStatDao;
import com.hundsun.cprs.yyt.service.account.domain.AccountStat;
import com.hundsun.cprs.yyt.service.account.service.AccountStatService;
import com.hundsun.cprs.yyt.service.common.Constants;
import com.hundsun.cprs.yyt.service.system.enums.EnumBussinessParam;
import com.hundsun.cprs.yyt.service.system.service.BusinessParamHelper;
import com.hundsun.cprs.yyt.service.system.service.BussinessParamService;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;

/**
 * 账户统计信息接口
 * @author herong22384
 * @date 20190304
 *
 * */
@Service
public class AccountStatServiceImpl extends BaseService implements AccountStatService {

    private static final String YYT_ACCOUNT_STAT_LOCK = Constants.YYT_ACCOUNT_STAT_LOCK;//用户统计信息变更锁

    @Autowired
    private AccountStatDao accountStatDao;
    @Autowired
    private RedisDistributedLock redisLock;
    @Autowired
    private BussinessParamService bussinessParamService;

    @Override
    public void updateAccountStat(AccountStat accountStat) {
        Validate.notNull(accountStat.getUserId(),"会员信息必填");
        String createLockKey = MessageFormat.format(YYT_ACCOUNT_STAT_LOCK, accountStat.getUserId());
        try{
            //获取创建锁,竞争则等待
            if(redisLock.lock(createLockKey)){
                AccountStat stat = this.selectAccountStat(accountStat.getUserId());
                if (stat != null){
                    accountStatDao.updateByPrimaryKeySelective(accountStat);
                }else{
                    accountStatDao.insert(accountStat);
                }
            }else{
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(), "无法获取用户统计信息变更锁[" + accountStat.getUserId() + "]");
            }
        }finally{
            redisLock.releaseLock(createLockKey);
        }
    }

    @Override
    public AccountStat selectAccountStat(Long userId) {
        return accountStatDao.selectByPrimaryKey(userId);
    }

    @Override
    public Boolean isNewUser(Long userId) {
        AccountStat accountStat = accountStatDao.selectByPrimaryKey(userId);
        if (accountStat == null){
            return true;
        }else{
            //从系统参数表中获取新人判断规则
            int sellTimeLimit = BusinessParamHelper.getIntValue(bussinessParamService,EnumBussinessParam.NEW_USER_RULE_LIMIT,3);
            if (Long.compare(accountStat.getTrusteTime(),sellTimeLimit)>0){
                return false;
            }else{
                return true;
            }
        }
    }
}
